<template>
  <div class="myecharts-container" :style="{ width: width, height: height }">
    <div :id="sid" class="myecharts-chart"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { random14 } from '@/util/utils.js'
export default {
  name: 'EchartHandler',
  props: {
    // 配置信息
    option: {
      type: Object,
      default: () => null,
    },
    width: {
      type: String,
      default: () => '100%',
    },
    height: {
      type: String,
      default: () => '100%',
    },
  },
  data() {
    return {
      sid: 'myEcharts_' + random14(),
      chartInstance: null,
    }
  },
  watch: {
    option(value) {
      if (this.chartInstance) {
        // console.log('>>>>>>>>>> option：', value)
        this.setOption(value)
      }
    },
  },
  mounted() {
    this.initChart()
  },
  beforeUnmount() {
    if (this.chartInstance) {
      this.chartInstance.dispose()
    }
  },
  methods: {
    // 初始化图表
    initChart() {
      const myChart = echarts.init(document.getElementById(this.sid))
      this.chartInstance = myChart
      // 绘制图表
      if (this.option) {
        this.setOption(this.option, true)
      }
    },
    setOption(newOption, flag) {
      // this.chartInstance && this.chartInstance.dispose()
      this.chartInstance && this.chartInstance.setOption(newOption, flag)
    },
    // 手动展示tooltip
    showtip(i) {
      // const _this = this
      this.chartInstance &&
        this.chartInstance.dispatchAction({
          type: 'showTip',
          seriesIndex: i,
        })
    },
  },
}
</script>
<style lang="scss" scoped>
.myecharts-container {
  width: 100%;
  height: 100%;

  .myecharts-chart {
    width: 100%;
    height: 100%;
  }
}
</style>
